from datetime import datetime
from typing import AsyncGenerator

from sqlalchemy.ext.asyncio.engine import create_async_engine
from sqlalchemy.ext.asyncio.session import async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.sql.sqltypes import DateTime

from settings import MYSQL_DATABASE, MYSQL_PWD, MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_CHARSET

# 连接url
url = f'mysql+aiomysql://{MYSQL_USER}:{MYSQL_PWD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset={MYSQL_CHARSET}'

# 创建引擎
engine = create_async_engine(url)

# 创建工厂函数
maker = async_sessionmaker(bind=engine, class_=AsyncSession)


async def get_session() -> AsyncGenerator[AsyncSession, None]:
    """
    获取会话
    """
    # 创建上下文管理器
    async with maker() as session:
        # 提出会话
        yield session


class BaseModel(DeclarativeBase):
    """orm 基类"""
    # 标记为抽象基类
    __abstract__: bool = True

    create_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now, comment="创建时间")
    update_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now, onupdate=datetime.now,
                                                comment="更新时间")
